package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.article.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {


    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult load2(ArticleHomeDto dto, boolean firstPage) {
        if(firstPage){
            String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if(StringUtils.isNotBlank(jsonStr)){
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                ResponseResult responseResult = ResponseResult.okResult(hotArticleVoList);
                return responseResult;
            }
        }
        List<ApArticle> apArticleList = load(dto, ArticleConstants.LOADTYPE_LOAD_MORE);
        return ResponseResult.okResult(apArticleList);
    }

    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null ||  user.getId() == null || user.getId() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        Integer userId = user.getId();
        boolean isfollow = false;
        boolean islike = false;
        boolean isunlike = false;
        boolean iscollection = false;

        Long articleId = dto.getArticleId();
        Integer authorId = dto.getAuthorId();

        Object like = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + articleId, userId.toString());
        if (like != null){
            islike = true;
        }
        Object unlike = cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + articleId, userId.toString());
        if (unlike != null){
            isunlike = true;
        }
        Object collection = cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + articleId, userId.toString());
        if (collection != null){
            iscollection = true;
        }
        Double follow = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, authorId.toString());
        if (follow != null){
            isfollow = true;
        }

        Map<String,Boolean> resultMap = new HashMap<>(4);
        resultMap.put("islike",islike);
        resultMap.put("isfollow",isfollow);
        resultMap.put("isunlike",isunlike);
        resultMap.put("iscollection",iscollection);

        return ResponseResult.okResult(resultMap);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult saveArticle(ArticleDto dto) {
        //文章保存的操作
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
        Long articleId = dto.getId();
        if (articleId == null){
            //文章id为空，说明不存在，需要对三张表都进行插入操作
            //插入article
            int articleInsert = apArticleMapper.insert(apArticle);
            if (articleInsert < 1){
                throw new RuntimeException("文章表插入失败");
            }

            //插入config
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setArticleId(apArticle.getId());
            apArticleConfig.setIsComment(true);
            apArticleConfig.setIsDown(true);
            apArticleConfig.setIsDown(false);
            apArticleConfig.setIsDelete(false);
            int configInsert = apArticleConfigMapper.insert(apArticleConfig);
            if (configInsert < 1){
                throw new RuntimeException("文章配置表插入失败");
            }
            //插入content
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            int contentInsert = apArticleContentMapper.insert(apArticleContent);
            if (contentInsert < 1){
                throw new RuntimeException("文章内容表插入失败");
            }

            articleFreemarkerService.buildArticleToMinIO(apArticle,dto.getContent());

            return ResponseResult.okResult(apArticle.getId());
        }else{
            //文章id不为空，说明文章已经存在，只需要对article和content表做修改即可
            //修改文章表
            int articleUpdate = apArticleMapper.updateById(apArticle);
            if (articleUpdate < 1){
                throw new RuntimeException("文章修改失败");
            }
            //修改文章内容表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(dto.getContent());
            apArticleContent.setArticleId(articleId);

            LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApArticleContent::getArticleId,articleId);

            int contentUpdate = apArticleContentMapper.update(apArticleContent, queryWrapper);
            if (contentUpdate < 1){
                throw  new RuntimeException("文章内容表修改失败");
            }

            articleFreemarkerService.buildArticleToMinIO(apArticle,dto.getContent());

            return ResponseResult.okResult(articleId);
        }
    }

    @Override
    public List<ApArticle> load(ArticleHomeDto dto, Short type) {
        List<ApArticle> apArticleList = apArticleMapper.load(dto,type);
        return apArticleList;
    }

}
